package com.hello.auth.service.impl;

import com.hello.auth.service.SysLoginService;
import com.hello.auth.service.SysPasswordService;
import com.hello.auth.service.SysRecordLogService;
import com.hello.common.core.constant.CacheConstants;
import com.hello.common.core.constant.Constants;
import com.hello.common.core.constant.SecurityConstants;
import com.hello.common.core.constant.UserConstants;
import com.hello.common.core.domain.R;
import com.hello.common.core.enums.UserStatus;
import com.hello.common.core.exception.ServiceException;
import com.hello.common.core.utils.StringUtils;
import com.hello.common.core.utils.ip.IpUtils;
import com.hello.common.redis.service.RedisService;
import com.hello.common.security.utils.SecurityUtils;
import com.hello.system.api.RemoteUserService;
import com.hello.system.api.RemoteWxService;
import com.hello.system.api.dto.SysUserDTO;
import com.hello.system.api.model.LoginUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;

/**
 * 登录校验方法实现
 * 
 * @author hello
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysLoginServiceImpl implements SysLoginService {
    private final RemoteUserService remoteUserService;
    private final RemoteWxService remoteWxService;
    private final SysPasswordService passwordService;
    private final SysRecordLogService recordLogService;
    private final RedisService redisService;

    /**
     * 登录
     */
    @Override
    public LoginUser login(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new ServiceException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new ServiceException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new ServiceException("用户名不在指定范围");
        }
        // IP黑名单校验
        String blackStr = redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST);
        if (StringUtils.isNotEmpty(blackStr) && IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new ServiceException("登录用户：" + username + " 不存在");
        }

        if (R.FAIL == userResult.getCode()) {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        SysUserDTO user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
        passwordService.validate(user, password);
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        return userInfo;
    }
    
    /**
     * 微信登录
     */
    @Override
    public LoginUser wxLogin(String code) {
        // 微信code为空 错误
        if (StringUtils.isBlank(code)) {
            recordLogService.recordLogininfor("微信登录", Constants.LOGIN_FAIL, "微信code必须填写");
            throw new ServiceException("微信code必须填写");
        }
        
        log.info("开始微信登录，code: {}", code);
        log.info("code字符详情: {}", code.chars().mapToObj(c -> String.format("%c(ASCII:%d)", (char)c, c)).collect(Collectors.joining(", ")));
        
        try {
            // 查询用户信息，这一步会在系统模块中调用微信API获取真正的openid
            // 如果用户不存在，系统模块会自动注册
            R<LoginUser> userResult = remoteUserService.getUserInfoByWxOpenid(code, SecurityConstants.INNER);
    
            if (R.FAIL == userResult.getCode()) {
                String errMsg = userResult.getMsg();
                log.error("微信登录失败: {}", errMsg);
                recordLogService.recordLogininfor("微信登录", Constants.LOGIN_FAIL, errMsg);
                throw new ServiceException(errMsg);
            }
    
            if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
                log.error("微信登录失败，无法获取用户信息");
                recordLogService.recordLogininfor("微信登录", Constants.LOGIN_FAIL, "无法获取用户信息");
                throw new ServiceException("微信登录失败，请重新获取登录凭证");
            }
    
            LoginUser userInfo = userResult.getData();
            SysUserDTO user = userResult.getData().getSysUser();
            
            if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
                recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
                throw new ServiceException("对不起，您的账号已被删除");
            }
            
            if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
                recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
                throw new ServiceException("对不起，您的账号已停用");
            }
            
            recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_SUCCESS, "微信登录成功");
            return userInfo;
        } catch (ServiceException e) {
            throw e;
        } catch (Exception e) {
            log.error("微信登录异常", e);
            recordLogService.recordLogininfor("微信登录", Constants.LOGIN_FAIL, "登录异常：" + e.getMessage());
            throw new ServiceException("微信登录异常，请稍后重试");
        }
    }

    @Override
    public void logout(String loginName) {
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功");
    }

    /**
     * 注册
     */
    @Override
    public void register(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            throw new ServiceException("用户/密码必须填写");
        }
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new ServiceException("账户长度必须在2到20个字符之间");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }

        // 注册用户信息
        SysUserDTO sysUser = new SysUserDTO();
        sysUser.setUserName(username);
        sysUser.setNickName(username);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

        if (R.FAIL == registerResult.getCode()) {
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(username, Constants.REGISTER, "注册成功");
    }

    /**
     * 获取微信OpenID
     */
    @Override
    public Map<String, Object> getWxOpenid(String code) {
        // 详细记录接收到的code
        log.info("接收到微信code原始值: [{}], 长度: {}", code, (code != null ? code.length() : 0));
        log.info("code字符详情: {}", code != null ? code.chars().mapToObj(c -> String.format("%c(ASCII:%d)", (char)c, c)).collect(Collectors.joining(", ")) : "null");
        
        if (StringUtils.isEmpty(code)) {
            throw new ServiceException("微信临时登录凭证code不能为空");
        }
        
        log.info("开始获取微信openid, code: {}", code);
        
        try {
            // 使用新增的微信用户服务接口获取微信openid
            Map<String, String> params = new HashMap<>();
            params.put("code", code);
            
            R<Map<String, Object>> wxInfoResult = remoteWxService.getWxOpenid(params, SecurityConstants.INNER);
            
            log.info("微信服务返回结果: {}", wxInfoResult);
            
            if (R.FAIL == wxInfoResult.getCode() || StringUtils.isNull(wxInfoResult.getData())) {
                String errorMsg = wxInfoResult.getMsg();
                log.error("获取微信openid失败: {}", errorMsg);
                throw new ServiceException(errorMsg != null ? errorMsg : "获取微信openid失败");
            }
            
            log.info("获取微信openid成功");
            
            return wxInfoResult.getData();
        } catch (Exception e) {
            log.error("处理微信openid请求异常: ", e);
            throw e;
        }
    }
    
    /**
     * 绑定微信openid到用户
     */
    @Override
    public R<Boolean> bindWxOpenid(String username, String openid) {
        log.info("绑定微信openid到用户: username={}, openid={}", username, openid);
        
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(openid)) {
            return R.fail("用户名或微信openid不能为空");
        }
        
        try {
            // 调用远程用户服务绑定openid
            R<Boolean> result = remoteUserService.bindWxOpenid(username, openid, SecurityConstants.INNER);
            
            if (result.getCode() == R.FAIL) {
                log.error("绑定微信openid失败: {}", result.getMsg());
                return result;
            }
            
            log.info("成功绑定微信openid到用户: {}", username);
            return R.ok(true);
        } catch (Exception e) {
            log.error("绑定微信openid异常", e);
            return R.fail("绑定微信openid异常: " + e.getMessage());
        }
    }
}